package net.cnki.sunny.base;

import net.cnki.sunny.util.StrUtil;
import com.kbase.jdbc.StatementImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DataContext<T> implements IDataContext {

    @Autowired
    private DataSourceKbaseManager kbaseDs;
    private static final Logger logger = LoggerFactory.getLogger(DataContext.class);
    private static boolean isUnicode = false;

    public DataContext() {
    }

    public <T> List<T> excuteQuery(String sql, Class<T> t) {
        List<T> result = null;
        ResultSet rs = null;
        Connection conn = null;
        StatementImpl pst = null;

        try {
            conn = this.kbaseDs.getConnection();
            pst = (StatementImpl) conn.createStatement();
            rs = pst.executeQuery(sql, false);
            result = this.handle(rs, this.parserFieldList(sql), t);
        } catch (Exception var16) {
            logger.error(sql);
            logger.error(var16.getMessage());
        } finally {
            try {
                if (rs != null && !rs.isClosed()) {
                    rs.close();
                }

                if (pst != null && !pst.isClosed()) {
                    pst.close();
                }

                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            } catch (Exception var15) {
                logger.error(var15.getMessage());
            }

        }

        return result;
    }

    public List<Map<String, String>> excuteQueryList(String sql) {
        List<Map<String, String>> result = new ArrayList();
        ResultSet rs = null;
        Connection conn = null;
        StatementImpl pst = null;

        try {
            conn = this.kbaseDs.getConnection();
            pst = (StatementImpl)conn.createStatement();
            rs = pst.executeQuery(sql, isUnicode);
            String[] fieldList = this.parserFieldList(sql);
            int count = fieldList.length;

            while(rs.next()) {
                Map<String, String> map = new HashMap();

                for(int i = 0; i < count; ++i) {
                    String name = fieldList[i].trim();
                    String value = rs.getString(i + 1);
                    map.put(name, value);
                }

                result.add(map);
            }
        } catch (Exception var20) {
            logger.error(sql);
            logger.error(var20.getMessage());
        } finally {
            try {
                if (rs != null && !rs.isClosed()) {
                    rs.close();
                }

                if (pst != null && !pst.isClosed()) {
                    pst.close();
                }

                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            } catch (Exception var19) {
                logger.error(var19.getMessage());
            }

        }

        return result;
    }

    public <T> T excuteQueryReturnOne(String sql, Class<T> t) {
        List<T> result = null;
        ResultSet rs = null;
        Connection conn = null;
        StatementImpl pst = null;

        try {
            conn = this.kbaseDs.getConnection();
            pst = (StatementImpl)conn.createStatement();
            rs = pst.executeQuery(sql, isUnicode);
            result = this.handle(rs, this.parserFieldList(sql), t);
        } catch (Exception var16) {
            logger.error(sql);
            logger.error(var16.getMessage());
        } finally {
            try {
                if (rs != null && !rs.isClosed()) {
                    rs.close();
                }

                if (pst != null && !pst.isClosed()) {
                    pst.close();
                }

                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            } catch (Exception var15) {
                logger.error(var15.getMessage());
            }

        }

        return result.size() > 0 ? result.get(0) : null;
    }


    public int excuteQueryRecordNumber(String sql) {
        int result = 0;
        ResultSet rs = null;
        Connection conn = null;
        StatementImpl pst = null;

        try {
            conn = this.kbaseDs.getConnection();
            pst = (StatementImpl)conn.createStatement();
            rs = pst.executeQuery(sql, isUnicode);
            if (rs.next() && rs.getString(1) != null) {
                result = Integer.parseInt(rs.getString(1));
            }
        } catch (Exception var15) {
            logger.error(sql);
            logger.error(var15.getMessage());
        } finally {
            try {
                if (rs != null && !rs.isClosed()) {
                    rs.close();
                }

                if (pst != null && !pst.isClosed()) {
                    pst.close();
                }

                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            } catch (Exception var14) {
                logger.error(var14.getMessage());
            }

        }

        return result;
    }


    private String[] parserFieldList(String sql) {
        String[] result = new String[0];

        try {
            sql = sql.toLowerCase();
            String field = sql.substring(7, sql.indexOf(" from"));
            result = field.split(",");

            for(int i = 0; i < result.length; ++i) {
                String str = result[i];
                if (str.contains(" as ")) {
                    int x = str.indexOf(" as ");
                    result[i] = str.substring(x + 4, str.length()).trim();
                } else {
                    result[i] = str.trim();
                }
            }
        } catch (Exception var7) {
            logger.error(sql);
            logger.error(var7.getMessage());
        }

        return result;
    }

    private <T> List<T> handle(ResultSet rs, String[] fieldList, Class<T> type) {
        ArrayList list = new ArrayList();

        try {
            int count = fieldList.length;

            while(rs.next()) {
                T t = null;

                for(int i = 0; i < count; ++i) {
                    String name = fieldList[i].trim();
                    String value = rs.getString(i + 1);
                    Field field = type.getDeclaredField(name);
                    if (StrUtil.checkStringNull(value) && t == null) {
                        t = type.newInstance();
                    }

                    if (field != null && t != null) {
                        field.setAccessible(true);
                        if (field.getType() == String.class) {
                            field.set(t, value);
                        } else if (field.getType() == Integer.TYPE) {
                            field.set(t, Integer.parseInt(value));
                        } else {
                            field.set(t, value);
                        }
                    }
                }

                if (t != null) {
                    list.add(t);
                }
            }
        } catch (Exception var11) {
            logger.error(var11.getMessage());
        }

        return list;
    }
}
